package net.xmmpp.uc.im.group.broker.consumer;

import net.xmmpp.uc.im.common.constants.Constants;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

public class MsgDOMReader {

    private static final Logger LOGGER = LoggerFactory.getLogger(MsgDOMReader.class);

    private static MsgDOMReader instance = new MsgDOMReader();

    private static ThreadLocal<SAXReader> readCache = new ThreadLocal<>();

    public static MsgDOMReader getInstance() {
        return instance;
    }

    private MsgDOMReader(){
    }

    private static SAXReader getLocalSAXReader() {
        SAXReader reader = readCache.get();
        if(reader == null) {
            reader = new SAXReader();
            readCache.set(reader);
        }

        return reader;
    }

    public String getMsgFirstChildName(Element root) {
        String name = null;

        Iterator<Element> elementIterator = root.elementIterator();
        while(elementIterator.hasNext()){
            Element elementIt = elementIterator.next();
            name = elementIt.getName();
        }

        return name;
    }

    public Element getMsgFirstChild(Element root) {
        Element child = null;

        Iterator<Element> elementIterator = root.elementIterator();
        while(elementIterator.hasNext()){
            child = elementIterator.next();
        }

        return child;
    }

    public String getElementAttr(Element element, String attrName) {
        return element.attributeValue(attrName);
    }

    public Element getRootElement(String xml) {
        Document document;
        Element root = null;

        try {
            document = DocumentHelper.parseText(xml);
            root = document.getRootElement();
        } catch (DocumentException e) {
            LOGGER.error("Parse Message Error", e);
        }

        return root;
    }

    public String setMsgVersion(String xml, long version) {
        Document document = null;
        try {
            document = DocumentHelper.parseText(xml);
            document.getRootElement().addAttribute(Constants.ATTR_VERSION, String.valueOf(version));

        } catch (DocumentException e) {
            LOGGER.error("Parse Message Error", e);
        }

        return document.getRootElement().asXML();
    }

    public String setMsgVersion(Element root, long version) {
        root.addAttribute(Constants.ATTR_VERSION, String.valueOf(version));

        return root.asXML();
    }

}
